#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QMessageBox>
#include <QNetworkDatagram>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    socket = new QUdpSocket(this);
    connect(socket,&QUdpSocket::readyRead,this,&Widget::processRequest);

    bool ret = socket->bind(QHostAddress::Any,8081);
    if(!ret)
    {
        QMessageBox::critical(nullptr,"服务器绑定失败",socket->errorString());
        return;
    }

}

Widget::~Widget()
{
    delete ui;
}

void Widget::processRequest()
{
    const QNetworkDatagram& requestDataGram = socket->receiveDatagram();
    QString request = requestDataGram.data();

    const QString& response = process(request);

    QNetworkDatagram responseDatagram(response.toUtf8(),requestDataGram.senderAddress(),requestDataGram.senderPort());
    QString log = "["+requestDataGram.senderAddress().toString()+":"+QString::number(requestDataGram.senderPort())+" req:"
            +request+" resp:"+response+"]";
    socket->writeDatagram(responseDatagram);

    ui->lineEdit->setText(log);
    ui->listWidget->addItem(log);
}

QString Widget::process(QString &string)
{
    return string;
}

